//
//  BPRefreshControl.swift
//  BPWeiBo
//  Created by apple on 16/4/14.
//  Copyright © 2016年 apple. All rights reserved.
/*
自定义一个控制器来替换我们的而tableView自带的控制器,来执行我们下拉刷新的操作
三种状态:普通状态;准备状态;正在刷新的状态
*/

import UIKit
import SnapKit
//定义刷新控件的高
private let refreshControlHeight:CGFloat = 60
//定义刷新空控件到多少后及开始刷新(导航条状态栏64,加上60行高)
private let startHeight:CGFloat = 124

//定义一个枚举来接收三种状态
enum BPRefresh: Int {
    case Normal = 0
    case WillPull = 1
    case Pulling = 2
}
class BPRefreshControl: UIControl {
    //初始化
    override init(frame: CGRect) {
        //设置frame
        let rect = CGRect(x: 0, y: -refreshControlHeight, width: ScreenWidth, height: refreshControlHeight)
        super.init(frame: rect)
        
        backgroundColor = UIColor.orangeColor()
        //设置控件的约束
        setUpUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //懒加载控件
    private lazy var textlbl = UILabel(text: "下拉刷新", textColor: BapiColor, fontSize: 12)
    private lazy var jiantouImg:UIImageView = {
        let imgView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
        
        return imgView
    }()
    private lazy var juhua:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    
    //设置一个scrollView来接收我们的父视图的scrollView
    var superScrollView = UIScrollView()
    
    //定义一个枚举的;类型
    var status:BPRefresh = .Normal {
        didSet{
        
            switch status {
            case .Normal:
                
                self.juhua.stopAnimating()
                if oldValue == .Pulling {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        var inset = self.superScrollView.contentInset
                        inset.top = inset.top - refreshControlHeight
                        self.superScrollView.contentInset = inset
                })
                
                }
            default : break
            }
        
        }

    }
    //设置控件的约束
    private func setUpUI() {
        addSubview(textlbl)
        addSubview(jiantouImg)
        addSubview(juhua)
        
        //设置约束
        self.textlbl.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
        }
        
        self.jiantouImg.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(textlbl.snp_centerY)
            make.centerX.equalTo(textlbl.snp_centerX).offset(-30)
        }
        self.juhua.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(textlbl.snp_centerY)
            make.centerX.equalTo(textlbl.snp_centerX).offset(-45)
        }
    }
    
    //MARK:获取父视图的偏移量,需要先获取父视图的scrollviewe,我们可以通过一个方法,就是子视图将要出现在父视图上的时候,来后去父视图scrollviewe
    override func willMoveToSuperview(newSuperview: UIView?) {
        //获取父视图的scrollView
        let superScrollView = newSuperview as! UIScrollView
        //获取父视图的contentofset
        //let contentoffset = superScrollView.contentOffset
        
        self.superScrollView = superScrollView
        //通过KVO来监听scrollView的偏移量的变化,从获取三种状态,来刷新自定义色视图,只能监听某个对象的属性,所以方法在对象上面
        /*
        observe:表示是谁来监听
        orKeyPath:观察的那个属性对应的key字符串
        options:表示观察是新值得变化还是旧值得变化
        */
        superScrollView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
    }
    
    //MARK:创建完观察者后一定要在deinit方法中移除观察者
    deinit {
        removeObserver(self, forKeyPath: "contentOffset")
    }
    
    //MARK:创建观察后,一定要实现观察的方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        //在这个方法中写上我们需要实现的代码
        let offSet = superScrollView.contentOffset.y
        //当小于124而且正在拖拽的时候就表示普通状态,当大于124就会表示马上要刷新的准备状态,当offset大于124而且处在准备状态就会进入正在刷新的状态
        if superScrollView.dragging {
            if offSet > -refreshControlHeight && status == .WillPull {
                //普通状态
                //print("普通状态")
                status = .Normal
                textlbl.text = "下拉刷新"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.jiantouImg.transform = CGAffineTransformIdentity
                })
                setUpHidden()
            }else if offSet < -refreshControlHeight && status == .Normal{
                //准备刷新
                //print("准备刷新")
                status = .WillPull
                //设置状态文字
                textlbl.text = "马上起飞"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.jiantouImg.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                setUpHidden()
                
            }
        } else {
            if status == .WillPull {
                //正在刷新
                status = .Pulling
                juhua.hidden = false
                textlbl.text = "正在刷新..."
                jiantouImg.hidden = true
                self.juhua.startAnimating()
                //self.status = .Normal
                //利用控制器可以发消息的方法,将消息发送给监听valuechange的类
                sendActionsForControlEvents(.ValueChanged)
    
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    var insert = self.superScrollView.contentInset
                    insert.top = refreshControlHeight + insert.top
                    self.superScrollView.contentInset = insert
                    })
                
                
            }
        }

    }
    
    private func setUpHidden() {
        juhua.hidden = true
        textlbl.hidden = false
        jiantouImg.hidden = false
    
    }
    
    func endRefreshing() {
        
        let delta = dispatch_time(DISPATCH_TIME_NOW,Int64(Double(NSEC_PER_SEC) * 0.9))
        dispatch_after(delta, dispatch_get_main_queue()) { () -> Void in
            self.status = .Normal
        }
        
    }
    
}
